<template>
  <div class="content">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">仓库管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/warehouseStock' }"
        >仓库库存</el-breadcrumb-item
      >
      <el-breadcrumb-item :to="{ path: '/wareUpdateList' }"
        >库存调整列表</el-breadcrumb-item
      >
      <el-breadcrumb-item v-if="iffix">修改库存调整</el-breadcrumb-item>
      <el-breadcrumb-item v-else>填写库存调整</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="context">
      <div class="left">
        <div class="top">库存调整单</div>
        <div class="tableBorder">
          <div class="title">
            <span v-if="iffix">调整编号：{{ content.oddNumbers }}</span>
            <span v-else>调整编号：{{ content.oddNumber }}</span>
            <span>
              <span>申请人：{{ content.createdByName }}</span>
              <span style="margin-left: 10px"
                >创建时间：{{ $moment(content.createdTime) }}</span
              >
            </span>
          </div>
          <el-table
            :data="tableData"
            ref="table"
            @selection-change="handleSelectionChange"
          >
            <!-- @row-click="openDetails" -->
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column
              label="序号"
              type="index"
              width="50"
            ></el-table-column>
            <el-table-column prop="title" label="商品信息" min-width="200">
              <template slot-scope="props">
                <p class="opli" @click="openDetail(props.row)">
                  {{ props.row.title }}
                </p>
              </template>
            </el-table-column>

            <el-table-column
              v-if="!iffix"
              prop="frontQuantity"
              label="原来库存"
            >
              <template slot-scope="props">
                <p class="opli" @click="openDetail(props.row)">
                  {{ props.row.frontQuantity }}
                </p>
              </template>
            </el-table-column>

            <el-table-column
              width="100"
              v-if="iffix"
              prop="frontQuantity"
              label="提交时库存"
            >
              <template slot-scope="props">
                <p class="opli" @click="openDetail(props.row)">
                  {{ props.row.frontQuantity }}
                </p>
              </template>
            </el-table-column>

            <el-table-column
              v-if="iffix"
              prop="realTimeQuantity"
              label="实时库存"
            >
              <template slot-scope="props">
                <p class="opli" @click="openDetail(props.row)">
                  {{ props.row.realTimeQuantity }}
                </p>
              </template>
            </el-table-column>

            <el-table-column prop="laterQuantity" label="调整库存">
              <template slot-scope="props">
                <p class="opli" @click="openDetail(props.row)">
                  {{ props.row.laterQuantity }}
                </p>
              </template>
            </el-table-column>

            <el-table-column label="调整数量">
              <template slot-scope="props">
                <p
                  class="opli"
                  @click="openDetail(props.row)"
                  v-if="
                    Number(props.row.laterQuantity) >
                    Number(props.row.frontQuantity)
                  "
                >
                  + {{ props.row.fixNum }}
                </p>
                <p class="opli" @click="openDetail(props.row)" v-else>
                  {{ props.row.fixNum }}
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="warAdName" label="调整原因" min-width="150">
              <template slot-scope="props">
                <p
                  class="opli"
                  v-if="props.row.warAdName"
                  @click="openDetail(props.row)"
                >
                  {{ props.row.warAdName }}
                </p>
                <p class="opli" v-else @click="openDetail(props.row)">无</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="right">
        <div class="title">
          <span>操作</span>
        </div>
        <!-- v-if="Object.keys(form).length" -->
        <el-form ref="form" :model="form" label-width="80px" v-if="nodate">
          <div>
            <el-form-item label="商品名称" v-if="show">
              <el-input size="small" v-model="form.title" disabled></el-input>
            </el-form-item>
            <el-form-item label="原来库存" v-if="show">
              <el-input
                size="small"
                v-model="form.wareTotal"
                disabled
              ></el-input>
            </el-form-item>

            <el-form-item label="仓库数量" v-if="show">
              <el-input
                size="small"
                v-model="form.wareNumber"
                disabled
              ></el-input>
            </el-form-item>

            <el-form-item label="调整仓库" v-if="form.warRequestList && show">
              <div
                v-for="(ite, index) in form.warRequestList"
                :key="index"
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <el-select
                  :value="ite.warName"
                  size="mini"
                  value-key="warId"
                  placeholder="请选择"
                  disabled
                >
                  <el-option
                    v-for="item in wareList.list"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  >
                  </el-option>
                </el-select>
                <div style="display: flex; align-items: center" v-if="show">
                  <el-input-number
                    v-if="iffix"
                    size="mini"
                    :min="0"
                    style="margin-right: 10px"
                    placeholder="请输入库存数量"
                    v-model="ite.realTimeQuantity"
                    @change="changeWareNumber(ite)"
                  ></el-input-number>

                  <el-input-number
                    v-else
                    size="mini"
                    :min="0"
                    style="margin-right: 10px"
                    placeholder="请输入库存数量"
                    v-model="ite.number"
                    @change="changeWareNumber(ite)"
                  ></el-input-number>
                </div>
              </div>
            </el-form-item>
          </div>

          <el-form-item label="调整原因">
            <el-select
              style="width: 100%"
              v-model="form.reson"
              ref="select"
              placeholder="请选择"
              size="mini"
              clearable
              value-key="id"
              @change="changeReson"
              @visible-change="(v) => visibleChange(v, 'select', selectClick)"
            >
              <el-option
                v-for="item in whyList.list"
                :key="item.id"
                :label="item.deliveryName"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <!-- 空数据 -->
        <div class="nodate" v-else>
          <img src="../../../../assets/kong.png" alt="" />
          <span>请选择左侧信息</span>
        </div>
      </div>
      <el-dialog
        title="管理调整原因"
        append-to-body
        width="30%"
        :visible.sync="dialogFormVisible"
      >
        <div class="dialogContent">
          <el-form label-width="80px">
            <el-form-item label="添加原因">
              <div class="add">
                <el-input v-model="whyValue" size="mini"></el-input
                ><i
                  style="margin-left: 20px; cursor: pointer"
                  class="el-icon-circle-plus-outline"
                  @click="addWhy"
                ></i>
              </div>
            </el-form-item>
          </el-form>
          <div
            class="whyList"
            style="pading: 2px 0px; height: 405px; overflow: auto"
          >
            <div
              v-for="(item, index) in whyList.list"
              :key="index"
              @dblclick="updateItem($event, item)"
              style="
                margin-bottom: 5px;
                display: flex;
                align-items: center;
                height: 40px;
                padding-left: 10px;
              "
            >
              <i
                v-if="id != item.id"
                class="el-icon-remove-outline"
                @click="deleteWhy(item.id)"
              ></i>
              <span v-if="id != item.id" style="margin-left: 10px">{{
                item.deliveryName
              }}</span>
              <input
                v-focus
                @blur="updateBlur($event.target.value, item)"
                v-if="id == item.id"
                type="text"
                style="height: 40px"
              />
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <div class="submit">
      <el-button size="mini" @click="$router.go(-1)">取消</el-button>
      <el-button size="mini" type="primary" @click="submitEvent"
        >提交</el-button
      >
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      id: "",
      whyValue: "",
      dialogFormVisible: false, //管理调拨原因的对话框
      tableData: [], //列表数据
      form: {}, //表单数据
      wareList: [], //仓库列表
      myWareList: [], //自己家的仓库列表
      whyList: {
        list: [],
      }, //调拨原因
      content: "",
      multipleSelection: [],
      iffix: false, //false为新增时，true为修改时
      show: false,
      nodate: false,
      cart: JSON.parse(localStorage.getItem("cart")),
    };
  },
  created() {
    this.axios
      .post("order/comm/commWarehouse/list",{
        pageSize:999,
        pageNo:1
      }, {
        headers: {
          isLoading: false,
        },
      })
      .then((res) => {
        //仓库数据接口
        if (res.code == 0) {
          this.wareList = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    this.getWhyList(); //原因列表
    this.iffix = this.$route.query.isCk;
    // if (this.$route.query.oddNumber) {
    //   this.iffix = true;
    //   this.fixAxios();
    // } else {
    // this.iffix = false;
    this.getList();
    // }
  },
  methods: {
    openDetail(row) {
      console.log(row);
      this.show = true;
      this.nodate = true;
      let wareNumber = ""; //仓库数量统计 A仓100

      for (let i in row.warRequestList) {
        // if (this.iffix) {
        wareNumber +=
          row.warRequestList[i].warName +
          row.warRequestList[i].frontQuantity +
          " ";
        // } else {
        //   wareNumber +=
        //     row.warRequestList[i].warName + row.warRequestList[i].number + " ";
        // }
      }

      this.form = row;
      this.$set(this, "form", row);
      this.$set(
        this.form,
        "reson",
        this.whyList.list.find((res) => res.id == row.warAdId)
      );

      this.$set(this.form, "wareNumber", wareNumber);
      this.$set(this.form, "wareTotal", row.frontQuantity);
    },
    handleSelectionChange(val) {
      // console.log(val);
      this.multipleSelection = val;
      // 详情为空且未选中
      if (
        Object.keys(this.form).length == 0 &&
        this.multipleSelection.length == 0
      ) {
        this.nodate = false;
        this.show = false;
      } else if (
        Object.keys(this.form).length &&
        this.multipleSelection.length == 1
      ) {
        this.nodate = true;
        // this.show = true;
        // 选中一个数据回显 //
        this.openDetail(val[0]);
      } else if (
        Object.keys(this.form).length == 0 &&
        this.multipleSelection.length == 1
      ) {
        this.nodate = true;
        // this.show = false;
        // 选中一个数据回显 //
        this.openDetail(val[0]);
      } else if (this.multipleSelection.length > 1) {
        this.show = false;
        this.nodate = true;
      } else if (Object.keys(this.form).length) {
        this.nodate = true;
        this.show = true;
      } else {
        this.nodate = false;
        this.show = false;
      }
    },
    // openDetails(row) {
    //   this.$refs.table.toggleRowSelection(row);
    // },
    changeWareNumber(e) {
      // console.log(e);
      let number = 0; //仓库加起来的数量；总数量
      let dvalue = 0; //改变后的差值

      if (!e.number) {
        e.number = 0;
      }
      // 多个仓库调整计算
      for (let j in this.form.warRequestList) {
        if (this.iffix) {
          number += Number(this.form.warRequestList[j].realTimeQuantity); //修改
        } else {
          number += Number(this.form.warRequestList[j].number);
        }

        if (this.form.warRequestList[j].warId == e.warId) {
          if (this.iffix) {
            this.form.warRequestList[j].number = e.realTimeQuantity; //修改
          } else {
            this.form.warRequestList[j].number = e.number;
          }
        }
      }

      if (this.iffix) {
        dvalue = number - Number(this.form.realTimeQuantity); //修改差
      } else {
        dvalue = number - Number(this.form.frontQuantity); //修改差
      }

      this.$set(this.form, "laterQuantity", number);
      this.$set(this.form, "fixNum", dvalue);
    },
    // 添加原因
    changeReson(e) {
      if (this.show) {
        this.$set(this.form, "warAdName", e.deliveryName);
        this.$set(this.form, "warAdId", e.id);
      } else {
        for (let i in this.multipleSelection) {
          this.$set(this.multipleSelection[i], "warAdName", e.deliveryName);
          this.$set(this.multipleSelection[i], "warAdId", e.id);
        }
      }
      this.$forceUpdate();
      // }
    },
    // 修改详情数据回显
    fixAxios() {
      this.axios
        .get(
          "/order/stockControl/allotDetails?oddNumber=" +
            this.$route.query.oddNumber,
          {
            headers: {
              isLoading: false,
            },
          }
        )
        .then((res) => {
          if (res.code == 0) {
            this.content = res.data;

            for (let i in res.data.goods) {
              for (let j in res.data.goods[i].warehouses) {
                res.data.goods[i].warehouses[j].frontQuantity =
                  res.data.goods[i].warehouses[j].number; //调拨前库存
              }

              let datelist = {
                title: res.data.goods[i].goodsName,
                goodsId: res.data.goods[i].goodsId,
                goodsType: res.data.goods[i].gtype,
                frontQuantity: res.data.goods[i].frontPracticalStock, //原来库存
                laterQuantity: 0, //修改库存
                realTimeQuantity: res.data.goods[i].realTimeQuantity,
                fixNum: 0,
                warAdId: res.data.goods[i].warAdId, //原因id
                warAdName: res.data.goods[i].warAdName, //原因
                warRequestList: res.data.goods[i].wars, //仓库
              };
              // console.log(datelist);

              this.tableData.push(datelist);
            }
          } else {
            this.$message.error(res.message);
          }
        });
    },
    //调整列表
    getList() {
      let obj = JSON.parse(this.$route.query.obj);
      this.axios
        .post("/order/stockControl/fillInAllotNumber", {
          gids: obj.gids,
          gtype: obj.gType,
          type: "TZ",
        })
        .then((res) => {
          if (res.code == 0) {
            this.content = res.data;

            for (let i in res.data.goodsList) {
              for (let j in res.data.goodsList[i].warehouses) {
                res.data.goodsList[i].warehouses[j].frontQuantity =
                  res.data.goodsList[i].warehouses[j].number; //调拨前库存
              }

              let datelist = {
                title: res.data.goodsList[i].title,
                goodsId: res.data.goodsList[i].id,
                goodsType: obj.gType, //商品类型:1：商品2：赠品
                frontQuantity: res.data.goodsList[i].quantityStock, //原来库存
                laterQuantity: 0, //修改库存
                fixNum: 0,
                warAdId: "", //原因id
                warAdName: "", //原因
                warRequestList: res.data.goodsList[i].warehouses, //仓库
              };

              this.tableData.push(datelist);
            }
          }
        });
    },
    updateBlur(e1, e2) {
      this.id = "";
      if (e1 == e2.deliveryName || !e1.replaceAll(" ", "").length) {
        this.$message.warning("名字没有任何改变");
        return;
      }
      this.axios
        .post("/order/warAdjustmentConfig/update", {
          request: {
            id: e2.id,
            deliveryName: e1,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.getWhyList();
            this.$message.success("修改成功");
          } else {
            this.$message.error(res.message);
          }
        });
    },
    updateItem(e1, e2) {
      this.id = e2.id;
    },
    draggableInput(e) {
      this.$set(this.whyList, "list", e);
    },
    //添加管理调拨原因
    addWhy: _.debounce(function () {
      if (this.whyValue.replaceAll(" ", "").length) {
        this.axios
          .post(
            "/order/warAdjustmentConfig/add",
            {
              request: {
                deliveryName: this.whyValue,
              },
            },
            {
              headers: {
                isLoading: false,
              },
            }
          )
          .then((res) => {
            if (res.code === 0) {
              this.$message.success("添加成功");
              this.whyValue = "";
              this.getWhyList();
            } else {
              this.$message.warning(res.message);
            }
          });
      } else {
        this.$message.warning("请输入调拨原因");
      }
    }, 500),
    deleteWhy(e) {
      this.axios
        .get("/order/warAdjustmentConfig/delete?id=" + e, {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          if (res.code === 0) {
            this.$message.success("删除成功");
            this.getWhyList();
          } else {
            this.$message.warning(res.message);
          }
        });
    },
    getWhyList() {
      this.axios
        .post(
          "/order/warAdjustmentConfig/list",
          {
            request: {},
          },
          {
            headers: {
              isLoading: false,
            },
          }
        )
        .then((res) => {
          if (res.code == 0) {
            this.whyList = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },

    //自己选择的仓库修改了
    // myWareListChange(e1, e2) {
    //   e2.id = e1.id;
    //   e2.name = e1.name;
    //   this.$forceUpdate();
    // },

    selectClick() {},
    //往el-select里面加入一个管理按钮
    visibleChange(visible, refName, onClick) {
      if (visible) {
        const ref = this.$refs[refName];
        let popper = ref.$refs.popper;
        if (popper.$el) popper = popper.$el;
        if (
          !Array.from(popper.children).some(
            (v) => v.className === "el-cascader-menu__list"
          )
        ) {
          const el = document.createElement("ul");
          el.className = "el-cascader-menu__list";
          el.style =
            "border-top: solid 1px #E4E7ED; padding:0; color: #606266;";
          el.innerHTML = `<li class="el-cascader-node" style="height:38px;line-height: 38px">
<i class="el-icon-menu"></i>
<span class="el-cascader-node__label">管理</span>
<i class="el-icon-arrow-right el-cascader-node__postfix"/>
</li>`;
          popper.appendChild(el);
          el.onclick = () => {
            // 底部按钮的点击事件 点击后想触发的逻辑也可以直接写在这
            this.getWhyList();
            this.dialogFormVisible = true;
            // 以下代码实现点击后弹层隐藏 不需要可以删掉
            if (ref.toggleDropDownVisible) {
              ref.toggleDropDownVisible(false);
            } else {
              ref.visible = false;
            }
          };
        }
      }
    },

    // 删除调整过的商品缓存//
    moreDelect() {
      let gids = JSON.parse(this.$route.query.obj).gids;

      for (let i = 0; i < gids.length; i++) {
        if (JSON.parse(this.$route.query.obj).gType == "1") {
          if (
            this.cart.goodList.find(
              (res) => res.id == JSON.parse(this.$route.query.obj).gids[i]
            )
          ) {
            this.cart.goodList = this.cart.goodList.filter(
              (res) => res.id != JSON.parse(this.$route.query.obj).gids[i]
            );
          }
        } else {
          this.cart.giftList = this.cart.giftList.filter(
            (res) => res.id != JSON.parse(this.$route.query.obj).gids[i]
          );
        }
      }

      localStorage.setItem(
        "cart",
        JSON.stringify({
          goodList: this.cart.goodList,
          giftList: this.cart.giftList,
        })
      );
    },
    // 提交
    submitEvent: _.debounce(function () {
      for (let i in this.tableData) {
        for (let j in this.tableData[i].warRequestList) {
          this.tableData[i].warRequestList[j].difference =
            this.tableData[i].warRequestList[j].number -
            this.tableData[i].warRequestList[j].frontQuantity; // this.tableData[i].fixNum;
          this.tableData[i].warRequestList[j].laterQuantity = this.tableData[
            i
          ].warRequestList[j].number;
          if (this.iffix) {
            this.tableData[i].warRequestList[j].frontQuantity = this.tableData[
              i
            ].realTimeQuantity; //重新定义值
          }
        }
      }

      if (this.iffix) {
        //修改后提交
        this.axios
          .post("/order/stockControl/updateAdjust", {
            createdById: this.content.createdById,
            createdByName: this.content.createdByName,
            createdTime: "",
            goodsList: this.tableData,
            oddNumber: this.content.oddNumbers,
            type: 2,
          })
          .then((res) => {
            // console.log(res);
            if (res.code == 0) {
              this.$message.success("修改成功");
              this.$router.push({ name: "wareUpdateList" });
            } else {
              this.$message.error(res.message);
            }
          });
      } else {
        //创建提交单
        this.axios
          .post("/order/stockControl/addAdjust", {
            createdById: this.content.createdById,
            createdByName: this.content.createdByName,
            createdTime: "",
            goodsList: this.tableData,
            oddNumber: this.content.oddNumber,
            type: 2,
          })
          .then((res) => {
            // console.log(res);
            if (res.code == 0) {
              if (!JSON.parse(this.$route.query.obj).isNewO) {
                this.moreDelect();
              }
              this.$message.success("提交成功");
              this.$router.push({ name: "wareUpdateList" });
            } else {
              this.$message.error(res.message);
            }
          });
      }
    }, 300),
  },
  directives: {
    focus: {
      inserted: (el) => {
        el.focus();
      },
    },
  },
};
</script>
<style scoped lang="scss">
.opli:hover {
  cursor: pointer;
}
.nodate {
  text-align: center;
  padding: 10px 0;
  img {
    width: 120px;
    height: 120px;
    display: block;
    margin: 0 auto;
  }
  span {
    font-size: 14px;
    color: #999;
    display: inline;
    margin-top: 10px;
  }
}
.submit {
  background: #fff;
  padding: 10px;
  margin: 10px 0;
  width: 99%;
  text-align: right;
  border-radius: 5px;
}
.content {
  .context {
    display: flex;
    width: 100%;
    height: 85%;
    margin-top: 20px;
    justify-content: space-between;
    min-width: 800px;
    min-height: 745px;
    .left {
      height: 100%;
      width: 59%;
      background: #fff;
      border-radius: 10px;
      padding: 10px 20px;
      box-sizing: border-box;
      .top {
        border-bottom: 1px solid #d9d9d9;
        padding: 10px 0px;
        font-size: 18px;
        color: #606060;
        line-height: 25px;
      }
      .tableBorder {
        border: 1px solid #d9d9d9;
        margin-top: 10px;
        .title {
          display: flex;
          flex-wrap: nowrap;
          justify-content: space-between;
          border-bottom: 1px solid #d9d9d9;
          font-size: 14px;
          padding: 10px 10px;
        }
      }
    }
    .right {
      width: 40%;
      height: 100%;
      border-radius: 10px;
      background: #fff;
      padding: 10px 20px;
      box-sizing: border-box;
      color: #333333;

      .title {
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #d9d9d9;
        padding: 10px 0px;
        margin-bottom: 5px;
      }
    }
  }
}
.dialogContent {
  .add {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .whyList {
    border: 1px solid #d9d9d9;
    margin-left: 10px;
    .item {
      margin-top: 10px;
      margin-left: 10px;
    }
  }
}
/deep/.el-table thead {
  color: #333;
}
</style>
